<template>
  <div class="ivy-database-main">
    <VRow class="ivy-database-row">
      <VCol cols="3">
        <VList
          class="ivy-database-list"
          nav
          :lines="false"
        >
          <VAutocomplete
            v-model="sqlManagerId"
            label="选择SQL管理器"
            :items="sqlManagerOptionList"
            item-title="smName"
            item-value="id"
            clearable
            style="overflow: hidden;margin-block-end: 12px;padding-block-start: 8px;text-overflow: ellipsis;white-space: nowrap;"
          />
          <VTextField
            v-model="filterTable"
            variant="outlined"
            label="筛选表名"
            prepend-inner-icon="tabler-filter"
            clearable
            style="margin-block-end: 12px;"
          />
          <div
            class="ivy-database-list-item"
            :style="getDynamicStyles()"
          >
            <VListItem
              v-for="item in filteredTables"
              :key="item.value"
              :value="item.value"
              @click="showTableData(item)"
            >
              <template #prepend>
                <VIcon
                  :icon="item.prependIcon"
                  class="me-3"
                />
              </template>

              <VListItemTitle>
                {{ item.title }}
              </VListItemTitle>
            </VListItem>
          </div>
        </VList>
      </VCol>
      <VCol cols="9">
        <VCard title="">
          <VCardText>
            <VRow>
              <VCol
                cols="12"
                sm="12"
              >
                <VTextField
                  v-model="text2sql"
                  variant="outlined"
                  label="在这里输入纯文本语句（文本转SQL）"
                  prepend-inner-icon="tabler-brand-openai"
                  clearable
                  style="margin-block-end: 12px;"
                />

                <Codemirror
                  ref="cmRef"
                  v-model:value="querySql"
                  :options="cmOptions"
                  height="150"
                  width="100%"
                  border
                  @change="onChange"
                  @input="onInput"
                  @ready="onReady"
                />
              </VCol>
            </VRow>
          </VCardText>

          <VDivider v-if="false" />

          <VCardText class="d-flex flex-wrap py-4 gap-4">
            <div class="me-3 d-flex gap-3">
              <VBtn prepend-icon="tabler-player-play">
                执行
              </VBtn> 
              <VBtn color="#fff">
                保存
              </VBtn> 
              <VBtn color="#fff">
                格式化
              </VBtn> 
            </div> 
           
            <VSpacer />

            <div class="d-flex align-center flex-wrap gap-4">
              <VMenu>
                <template #activator="{ props }">
                  <VBtn
                    color="primary"
                    v-bind="props"
                    prepend-icon="tabler-table-export"
                  >
                    导出
                  </VBtn>
                </template>

                <VList :items="exportItems" />
              </VMenu>

              <VBtn
                size="38"
                @click="fetchList"
              >
                <VIcon
                  icon="tabler-refresh"
                  size="22"
                />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  刷新
                </VTooltip>
              </VBtn>
              <!--
                <VBtn
                prepend-icon="tabler-plus"
                @click="addOper"
                >
                新增
                </VBtn> 
              -->
            </div>
          </VCardText>

          <VDivider />

          <VDataTableServer
            v-model:items-per-page="options.itemsPerPage"
            v-model:page="options.page"
            :items="list"
            :items-length="totalRows"
            :headers="headers"
            class="text-no-wrap"
            :height="listItemHeight - 160"
            fixed-header
            density="compact"
            
            @update:options="options = $event"
          >

            <template v-slot:headers="{ columns, isSorted, getSortIcon, toggleSort }">
              <tr>
                <template v-for="column in columns" :key="column.key">
                  <td>
                    <span class="cursor-pointer" @click="() => toggleSort(column)">{{ column.title }}</span>
                    <template v-if="isSorted(column)">
                      <v-icon :icon="getSortIcon(column)"></v-icon>
                    </template>
                    <v-icon v-if="column.removable" icon="$close" @click="() => removeHeaders(column.key)"></v-icon>
                  </td>
                </template>
              </tr>
            </template>

            <!--
              <template #item.chainId="{ item }">
              <span class="font-weight-medium">{{ item.raw.chainId }}</span>
              </template>

              <template #item.chainName="{ item }">
              <span class="font-weight-medium">{{ item.raw.chainName }}</span>
              </template>   
            -->
           
           
            <!--
              <template #item.actions="{ item }">
              <IconBtn @click="deleteOper(item.raw.id)">
              <VIcon icon="tabler-trash" />
              <VTooltip
              activator="parent"
              location="top"
              >
              删除
              </VTooltip>
              </IconBtn>

              <IconBtn @click="updateOper(item.raw)">
              <VIcon icon="tabler-edit" />
              <VTooltip
              activator="parent"
              location="top"
              >
              编辑
              </VTooltip>
              </IconBtn>
              </template> 
            -->

            
            <template #bottom>
              <VDivider />
              <div class="d-flex align-center justify-sm-space-between justify-center flex-wrap gap-3 pa-5 pt-3">
                <p class="text-sm text-disabled mb-0">
                  共<span style="color: #7367f0;">&nbsp;{{ totalRows }}&nbsp;</span>条记录
                </p>
                <AppSelect
                  :model-value="options.itemsPerPage"
                  :items="[
                    { value: 10, title: '10' },
                    { value: 20, title: '20' },
                    { value: 50, title: '50' },
                    { value: 100, title: '100' },
                    { value: 200, title: '200' },
                    { value: 500, title: '500' },
                    { value: 1000, title: '1000' },
                  ]"
                  style="inline-size: 6.25rem;"
                  @update:model-value="options.itemsPerPage = parseInt($event, 10)"
                />
                <VPagination
                  v-model="options.page"
                  :length="Math.ceil(totalRows / options.itemsPerPage)"
                  :total-visible="$vuetify.display.xs ? 1 : Math.ceil(totalRows / options.itemsPerPage)"
                >
                  <template #prev="slotProps">
                    <!--
                      <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                      style="margin-right: 8px;"
                      >
                      <VIcon
                      icon="tabler-chevrons-left"
                      size="22"
                      />
                      </VBtn> 
                    -->
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      上一页
                    </VBtn>
                  </template>

                  <template #next="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      下一页
                    </VBtn>
                    <!--
                      <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                      style="margin-left: 8px;"
                      >
                      <VIcon
                      icon="tabler-chevrons-right"
                      size="22"
                      />
                      </VBtn> 
                    -->
                  </template>
                </VPagination>
              </div>
            </template>
          </VDataTableServer>
        </VCard>
      </VCol>
    </VRow>
  </div>
</template>

<script setup>
import Codemirror from "codemirror-editor-vue3"
import 'codemirror/addon/hint/show-hint'
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/hint/sql-hint'
import "codemirror/mode/sql/sql"
import { onMounted, onUnmounted, reactive, ref, watchEffect } from 'vue'
import { VDataTableServer } from 'vuetify/labs/VDataTable'

// 代码编辑器
const cmRef = ref()

const cmOptions = {
  mode: "text/x-sql",
  extraKeys: { // 触发按键
    'Ctrl': 'autocomplete',
  },
  hintOptions: {
    completeSingle: false,
    tables: {
      // 在这里提供你的数据库表信息
      users: ['column1', 'column2', 'column3'],
      config: ['columnA', 'columnB', 'columnC'],
    },
  },
}

const onChange = (val, cm) => {
  //console.log(val)
  //console.log(cm.getValue())
  cm.showHint()
}

const onInput = val => {
  //console.log(val)
}

const onReady = cm => {
  //console.log(cm.focus())
}

const querySql = ref()
const text2sql = ref()

// 分页列表
const totalPage = ref(1)
const totalRows = ref(0)
const list = ref([])
const headers = reactive([]) // 表头

// 分页参数
const options = ref({
  page: 1,
  itemsPerPage: 10,
  sortBy: [],
  groupBy: [],
  search: undefined,
})

const sqlManagerId = ref()
const listItemHeight = ref(0)
const filterTable = ref('')
const filteredTables = ref([])

// 初始化
onMounted(() => {
  sqlManagerOptionSelect()

  const myElement = document.querySelector('.ivy-database-list-item')
  if (myElement) {
    const rect = myElement.getBoundingClientRect()

    listItemHeight.value = rect.height
  }

  setTimeout(() => {
    cmRef.value?.refresh()
  }, 100)
})

onUnmounted(() => {
  cmRef.value?.destroy()
})

const getDynamicStyles = () => {
  const myElement = document.querySelector('.ivy-database-list-item')


  if (myElement) {
    return {
      height: (listItemHeight.value + 100) + "px", // 你的动态样式属性
      overflowY: 'scroll',
    }
  } else {
    return { height: '100%' }
  }
}

const tables = reactive([])

const sqlManagerOptionList = reactive([])

const sqlManagerOptionSelect = async () => {
    const res = await $ivyApi.post(API_URLS.sqlManagerOptions,{})
    sqlManagerOptionList.push(...res.data)
}

const currTableName = ref()

const showTableData = item => {
  currTableName.value = item.value
}

const removeHeaders = key => {
  const arr = headers.filter(header => header.key != key)

  headers.length = 0
  headers.push(...arr)
}

const fetchList = async () => {
  const res = await $ivyApi.post(API_URLS.dbTableData,{
    id: sqlManagerId.value,
    tableName: currTableName.value,
    options: options.value,
  })

  if(res.data){
    const data = res.data
    let response = data.pageResult
    let columnList = data.columnList
    list.value = response.list
    totalPage.value = response.totalPage
    totalRows.value = response.totalRow
    options.value.page = response.page
    headers.length = 0
    headers.push(...columnList)
  }
}

watchEffect(fetchList)
// 监听 options 对象的变化，并在变化时调用 fetchList 方法
watch(options, async () => { await fetchList() }, { deep: true })

watch(sqlManagerId, val => {
  tables.length = 0
  if(sqlManagerId.value){
    queryDbTables()
  }
})

const queryDbTables = async () => {
  const res = await $ivyApi.post(API_URLS.dbTables,{
    id: sqlManagerId.value,
  })
  tables.push(...res.data)
}

watchEffect(() => {
  filteredTables.value = tables.filter(table => 
    table.value.toLowerCase().includes(filterTable.value.toLowerCase()),
  )
})

const exportItems = [
  {
    title: '导出结果集 CSV',
    value: '1',
  },
  {
    title: '导出结果集 INSERT SQL',
    value: '2',
  },
]
</script>

<style scoped>
.ivy-database-main,
.ivy-database-list {
  block-size: 100%;
  inline-size: 100%;
  overflow-y: hidden;
}

.ivy-database-row {
  block-size: 100%;
  inline-size: 100%;
}

.ivy-database-main {
  min-inline-size: 300px;
}
</style>
